package com.touch.graphingutil;

import java.awt.Color;
import java.awt.Graphics;
public class JLineGraph extends JGraph
{
	private static final long serialVersionUID = 7849931506548380686L;
	private int increment;
	private int position;
	
	public JLineGraph(String title, int min, int max) 
	{
	   super(title, min, max);
	}
	public int getScaleY(final int index)
	{
		return bottom - ((index - min) * (bottom - top))/(max - min);
	}
	public int getScaleX(final int index)
	{
		return this.position + index * (this.increment);
	}
	public int getItemIndex(final int x)
	{
		return (x - this.position) / this.increment;
	}
	public int getItemValue(final int y)
	{		
		return min + (( y - bottom) * (min - max)) / (bottom - top);
	}
	public void paintComponent(Graphics g) 
	{
	    super.paintComponent(g);	    
	    if(this.items.isEmpty())
	    	return;
	    final Color temp = g.getColor();	    
	    final GraphItem firstItem = (GraphItem)items.firstElement();
	    final int firstAdjustedValue = bottom - (((firstItem.value - min)*(bottom - top))/(max - min));
	    
	    this.increment = (this.right - this.left)/(this.items.size() - 1);
	    this.position = left;	    	  
	    
	    g.setColor(firstItem.color);
	    g.drawString(firstItem.title, position - fm.stringWidth(firstItem.title), firstAdjustedValue - 2);
	    g.fillOval(position - 2, firstAdjustedValue - 2, 4, 4);
	    g.setColor(temp);
	    
	    for (int i = 0; i < items.size() - 1; i++) 
	    {
	       final GraphItem thisItem = (GraphItem)items.elementAt(i);	       
	       final GraphItem nextItem = (GraphItem)items.elementAt(i+1); 	       
	       final int thisAdjustedValue = getScaleY(thisItem.value);
	       final int nextAdjustedValue = getScaleY(nextItem.value);
	       
	       //g.drawLine(position, thisAdjustedValue, position+=increment, nextAdjustedValue);
	       g.drawLine(getScaleX(i), thisAdjustedValue, getScaleX(i + 1), nextAdjustedValue);	       
	       g.setColor(nextItem.color);
	       
	       if (nextAdjustedValue < thisAdjustedValue)
	    	   g.drawString(nextItem.title, position - fm.stringWidth(nextItem.title), 
	    			   nextAdjustedValue + titleHeight + 4);
	       else
	          g.drawString(nextItem.title, position - fm.stringWidth(nextItem.title),
	                   nextAdjustedValue - 4);
	       
	       g.fillOval(getScaleX(i + 1) - 2, nextAdjustedValue - 2, 4, 4);	              	      
	       g.setColor(temp);
	    }
	}
}